package com.yunzheng.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunzheng.common.BaseResult;
import com.yunzheng.dto.ChangeProjectContentDTO;
import com.yunzheng.dto.ChangeProjectInfoDTO;
import com.yunzheng.dto.NewProjectDTO;
import com.yunzheng.entity.ExcelProject;
import com.yunzheng.entity.Project;
import com.yunzheng.exception.ServiceException;
import com.yunzheng.service.ProjectService;
import com.yunzheng.util.DtoUtil;
import com.yunzheng.util.FtpUploadFile;
import com.yunzheng.util.TokenParser;
import com.yunzheng.vo.ProjectListVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 郭思良
 * @create 2020-07-28 16:13
 */


@RestController
@RequestMapping("/project")
@Api(tags = "多项目管理")
@Slf4j
public class ProjectController {

	@Resource
	private ProjectService projectService;

	/**
	 * 向后台传入`项目名称`,`项目负责人名称`,`项目指导老师名称`,`项目起止时间`,`项目等级`,`项目描述`
	 * 自动生成`项目ID=最大ID+1`,`项目SID=0`,`项目状态=0`,`工期=结束时间-起始时间`,`迭代数=0`,`团队名=项目负责人所在的团队`
	 * <p>
	 * input代表新建项目的主要信息
	 * <p>
	 * /post -- authc
	 */
	@ApiOperation(value = "1.新建项目接口", notes = "projectManager和partyA不传ID，传名字\n" +
			"level、description、workTime可以为空，其余不可以为空\n" +
			"level传入String类型，不是Integer类型，workTime是Integer类型的")
	@PostMapping("/post")
	public BaseResult postNewProject(@Valid @RequestBody NewProjectDTO input) {
		projectService.postNewProject(input);
		return BaseResult.ok();
	}

	/**
	 * 分页展示出所有项目的列表
	 * offset 页数
	 * <p>
	 * /show/list -- authc
	 */
	@ApiOperation(value = "2.展示所有项目列表", notes = "offset是分页传入的页数，每页默认10条记录")
	@GetMapping("/show/list")
	public BaseResult listAllProjects(Integer offset) {
		// TODO: 2020/8/11 根据项目状态 全部项目-1、未开始0、进行中1、已完成2 来列出项目
		return BaseResult.ok(projectService.listAllProjects(offset));
	}

	/**
	 * 对项目列表的基本信息进行修改
	 * input 修改项目基本信息
	 * <p>
	 * /change -- roles[2]
	 */
	@ApiOperation(value = "3.修改项目基本信息", notes = "projectManager和partyA不传ID，传名字\n" +
			"level、workTime可以为空，其余不可以为空，projectStatus的范围在(0~2)之间\n" +
			"level传入String类型，不是Integer类型，workTime是Integer类型的")
	@PutMapping("/change")
	public BaseResult changeProjectInfo(@Valid @RequestBody ChangeProjectInfoDTO input) {
		projectService.changeProjectInfo(input);
		return BaseResult.ok();
	}

	/**
	 * 根据 项目id、项目名称、团队名、甲方、项目负责人 等信息进行搜索。
	 * <p>
	 * /search -- authc
	 */
	@ApiOperation(value = "4.根据搜索条件筛选项目接口", notes = "key是搜索条件的关键字")
	@GetMapping("/search")
	public BaseResult searchProjectByKey(String key) {
		// 查询符合条件的project
		List<Project> projects = projectService.list(new QueryWrapper<Project>().like(Project.COL_PROJECT_ID, key).or().like(Project.COL_PROJECT_NAME, key).or()
				.like(Project.COL_PROJECT_MANAGER, key).or().like(Project.COL_PARTY_A, key).or().like(Project.COL_TEAM, key).eq(Project.COL_PROJECT_SID, 0));
		return BaseResult.ok(projectService.listProjectsByKey(projects));
	}

	/**
	 * 删除该项目
	 * /remove -- roles[2]
	 */
	@ApiOperation(value = "5.删除项目接口")
	@DeleteMapping("/remove")
	public BaseResult removeProject(String projectId) {
		projectService.removeProject(projectId);
		return BaseResult.ok();
	}

	/**
	 * 展示该项目的具体信息
	 * <p>
	 * /show/one -- authc
	 */
	@ApiOperation("6.展示具体项目信息接口")
	@GetMapping("/show/one")
	public BaseResult showProjectContent(String projectId) {
		return BaseResult.ok(projectService.showProjectContent(projectId));
	}

	/**
	 * 修改项目内的具体信息
	 * <p>
	 * /change/one -- roles[2]
	 */
	@ApiOperation("7.修改项目具体信息")
	@PutMapping("/change/one")
	public BaseResult changeProjectContent(@Valid @RequestBody ChangeProjectContentDTO input) {
		Project project = new Project();
		BeanUtils.copyProperties(input, project);
		System.out.println(project.toString());
		projectService.saveOrUpdate(project);
		return BaseResult.ok();
	}

	/**
	 * 导入项目模块
	 * <p>
	 * /import -- roles[1]
	 */
	@ApiOperation("8.导入项目")
	@PostMapping("/import")
	public BaseResult importExcel(@RequestParam("file") MultipartFile file) {
		try {
			projectService.saveBatch(getProjectList(file));
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("导入文件出现错误");
		}
		return BaseResult.ok();
	}

	/**
	 * 导出项目模块
	 * <p>
	 * /export -- roles[1]
	 */
	@ApiOperation("9.导出项目模块")
	@PostMapping("/export")
	public ModelAndView exportExcel(@Valid @RequestBody List<ProjectListVO> vos) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		//导出文件名称
		mv.addObject(NormalExcelConstants.FILE_NAME, "Project Progress Overview-" + sdf.format(new Date()));
		//注解对象Class
		mv.addObject(NormalExcelConstants.CLASS, ProjectListVO.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("项目进度概览", "项目进度概览"));
		//导出数据列表
		mv.addObject(NormalExcelConstants.DATA_LIST, vos);
		return mv;
	}


	/**
	 * 批量删除项目接口
	 * <p>
	 * /removeAll -- roles[1]
	 */
	@ApiOperation("10.批量删除项目接口")
	@DeleteMapping("/removeAll")
	public BaseResult removeProjects(@RequestParam(value = "projectIds") List<String> projectIds) {
		if (projectIds.size() == 0) {
			throw new ServiceException("请选择要删除的项目ID");
		}
		projectService.removeProjects(projectIds);
		return BaseResult.ok();
	}


	/**
	 * 从文件中取出项目列表，填充到数据库中
	 */
	private List<Project> getProjectList(MultipartFile file) throws Exception {
		// 设置 EXCEL 参数
		ImportParams params = new ImportParams();
		params.setTitleRows(1);
		//上传文件至云端
		FtpUploadFile.uploadFile(file.getOriginalFilename(), (FileInputStream) file.getInputStream());
		List<ExcelProject> projectList = ExcelImportUtil.importExcel(file.getInputStream(), ExcelProject.class, params);
		//转换星级
		for (ExcelProject project : projectList) {
			project.setLevel(String.valueOf(project.getLevel().length()));
		}
		//将ExcelProject转换成为Project
		List<Project> list = new ArrayList<>();
		for (ExcelProject excelProject : projectList) {
			Project project = DtoUtil.toEntity(excelProject, Project.class);
			list.add(project);
		}
		return list;
	}

	/**
	 * 展示我所参与的项目
	 * <p>
	 * /mine -- authc
	 */
	@ApiOperation("11.我参与的项目")
	@GetMapping("/mine")
	public BaseResult myJoinProject(HttpServletRequest request) {
		return BaseResult.ok(projectService.myJoinProject(TokenParser.token2UserId(request)));
	}

	/**
	 * 展示我所负责的项目
	 * <p>
	 * /mineRes -- authc
	 */
	@ApiOperation("12.我负责的项目")
	@GetMapping("/mineRes")
	public BaseResult myResponsibleProject(HttpServletRequest request) {
		return BaseResult.ok(projectService.myResponsibleProject(TokenParser.token2UserId(request)));
	}

	/**
	 * 获得所有项目和所有项目的个数
	 * <p>
	 * count -- anon
	 */
	@ApiOperation("13.返回所有项目的个数")
	@GetMapping("/count")
	public BaseResult listProjectCount() {
		List<Project> projects = projectService.list(new QueryWrapper<Project>().eq(Project.COL_PROJECT_SID, 0));
		return BaseResult.ok(projects);
	}

	/**
	 * 我的多项目管理
	 * <p>
	 * /list/mine -- authc
	 */
	@ApiOperation(value = "我的多项目管理")
	@GetMapping("/list/mine")
	public BaseResult listMyProjects(HttpServletRequest request) {
		return BaseResult.ok(projectService.listMyProjects(TokenParser.token2UserId(request)));
	}


}
